<template>
  <div class="qrcode-edit-container">
    <!-- 顶部导航 -->
    <div class="edit-header">
      <a-button type="text" @click="goBack" class="back-btn">
        <template #icon>
          <ArrowLeftOutlined />
        </template>
        返回
      </a-button>
      <div class="header-content">
        <div class="edit-info">
          <EditOutlined class="edit-icon" />
          <div class="edit-meta">
            <h1 class="edit-title">{{ isCreate ? '➕ 新增聚合码牌' : '✏️ 编辑聚合码牌' }}</h1>
            <div class="edit-subtitle">
              {{ isCreate ? '创建新的聚合码牌' : `编辑码牌：${qrForm.qrName || qrForm.qrCode}` }}
            </div>
          </div>
        </div>
        <div class="header-actions">
          <a-button @click="goBack" style="margin-right: 12px;">取消</a-button>
          <a-button type="primary" @click="handleSave" :loading="saving">
            <template #icon>
              <SaveOutlined />
            </template>
            保存
          </a-button>
        </div>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="edit-content">
      <a-row :gutter="24">
        <!-- 左侧：表单 -->
        <a-col :span="16">
          <a-card title="基本信息" class="form-card">
            <a-form
              :model="qrForm"
              :rules="qrRules"
              ref="qrFormRef"
              layout="vertical"
              :label-col="{ span: 24 }"
              :wrapper-col="{ span: 24 }"
            >
              <!-- 基本信息 -->
              <div class="form-section">
                <h3 class="section-title">📝 基本信息</h3>
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="聚合码牌名称" name="qrName">
                      <a-input
                        v-model:value="qrForm.qrName"
                        placeholder="请输入聚合码牌名称"
                        size="large"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="聚合码牌代码" name="qrCode">
                      <a-input
                        v-model:value="qrForm.qrCode"
                        placeholder="请输入聚合码牌代码"
                        size="large"
                        :disabled="!isCreate"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>

              <!-- 商户信息 -->
              <div class="form-section">
                <h3 class="section-title">🏪 商户信息</h3>
                <a-form-item label="所属商户" name="merchantId">
                  <a-select
                    v-model:value="qrForm.merchantId"
                    placeholder="请选择所属商户"
                    size="large"
                    show-search
                    :filter-option="filterMerchantOption"
                    @change="handleMerchantChange"
                  >
                    <a-select-option
                      v-for="merchant in availableMerchants"
                      :key="merchant.merchantId"
                      :value="merchant.merchantId"
                    >
                      <div class="merchant-option">
                        <div class="merchant-name">{{ merchant.merchantName }}</div>
                        <div class="merchant-id">{{ merchant.merchantId }}</div>
                      </div>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </div>

              <!-- 配置信息 -->
              <div class="form-section">
                <h3 class="section-title">⚙️ 配置信息</h3>
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="有效期" name="validPeriod">
                      <a-select v-model:value="qrForm.validPeriod" placeholder="请选择有效期" size="large">
                        <a-select-option value="永久有效">永久有效</a-select-option>
                        <a-select-option value="7天">7天</a-select-option>
                        <a-select-option value="15天">15天</a-select-option>
                        <a-select-option value="30天">30天</a-select-option>
                        <a-select-option value="90天">90天</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="状态" name="qrStatus">
                      <a-select v-model:value="qrForm.qrStatus" size="large">
                        <a-select-option :value="1">
                          <div class="status-option">
                            <CheckCircleOutlined style="color: #52c41a; margin-right: 6px;" />
                            启用
                          </div>
                        </a-select-option>
                        <a-select-option :value="0">
                          <div class="status-option">
                            <StopOutlined style="color: #999; margin-right: 6px;" />
                            停用
                          </div>
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>

              <!-- APP绑定信息 -->
              <div class="form-section">
                <h3 class="section-title">📱 APP绑定</h3>
                <a-form-item label="绑定APP">
                  <a-select
                    v-model:value="qrForm.boundAppId"
                    placeholder="请选择要绑定的APP（可选）"
                    size="large"
                    allow-clear
                    show-search
                    :filter-option="filterAppOption"
                    @change="handleAppChange"
                  >
                    <a-select-option
                      v-for="app in availableApps"
                      :key="app.appId"
                      :value="app.appId"
                    >
                      <div class="app-option">
                        <div class="app-name">{{ app.appName }}</div>
                        <div class="app-info">
                          {{ getAppTypeName(app.appType) }} | {{ app.merchantName }}
                        </div>
                      </div>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </div>
            </a-form>
          </a-card>
        </a-col>

        <!-- 右侧：预览和提示 -->
        <a-col :span="8">
          <!-- 预览区域 -->
          <a-card title="聚合码牌预览" class="preview-card">
            <div class="qr-preview">
              <div class="qr-visual">
                <QrcodeOutlined class="qr-large-icon" />
                <div class="qr-info-overlay">
                  <div class="qr-name">{{ qrForm.qrName || '聚合码牌名称' }}</div>
                  <div class="qr-code-text">{{ qrForm.qrCode || 'QR代码' }}</div>
                  <a-tag :color="getQrStatusColor(qrForm.qrStatus)" size="small">
                    {{ getQrStatusName(qrForm.qrStatus) }}
                  </a-tag>
                </div>
              </div>
              <div class="qr-details">
                <a-descriptions size="small" :column="1">
                  <a-descriptions-item label="所属商户">
                    {{ selectedMerchant?.merchantName || '未选择' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="绑定APP">
                    {{ selectedApp?.appName || '未绑定' }}
                  </a-descriptions-item>
                  <a-descriptions-item label="有效期">
                    {{ qrForm.validPeriod || '未设置' }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
          </a-card>

          <!-- 操作提示 -->
          <a-card title="💡 操作提示" class="tips-card" style="margin-top: 16px;">
            <div class="tips-content">
              <a-alert
                type="info"
                show-icon
                style="margin-bottom: 12px;"
              >
                <template #message>
                  <div>聚合码牌代码创建后不可修改</div>
                </template>
              </a-alert>

              <a-alert
                type="warning"
                show-icon
                style="margin-bottom: 12px;"
              >
                <template #message>
                  <div>请确保商户信息正确，影响支付流程</div>
                </template>
              </a-alert>

              <a-alert
                type="success"
                show-icon
              >
                <template #message>
                  <div>绑定APP后可以接收支付回调</div>
                </template>
              </a-alert>
            </div>
          </a-card>

          <!-- 快捷操作 -->
          <a-card title="🚀 快捷操作" class="actions-card" style="margin-top: 16px;">
            <a-space direction="vertical" style="width: 100%;">
              <a-button block @click="generateQrCode">
                <template #icon>
                  <ReloadOutlined />
                </template>
                自动生成代码
              </a-button>
              <a-button block @click="previewGenerated">
                <template #icon>
                  <EyeOutlined />
                </template>
                预览生成效果
              </a-button>
              <a-button block @click="testConnection" :disabled="!qrForm.boundAppId">
                <template #icon>
                  <ApiOutlined />
                </template>
                测试APP连接
              </a-button>
            </a-space>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  EditOutlined,
  SaveOutlined,
  QrcodeOutlined,
  CheckCircleOutlined,
  StopOutlined,
  ReloadOutlined,
  EyeOutlined,
  ApiOutlined
} from '@ant-design/icons-vue'
import {
  qrCodes,
  getQrStatusName,
  getQrStatusColor,
  generateQrUrl,
  generateQrContent,
  type QRCode
} from '@/mock'
import { appConfigs, getAppTypeName, type AppConfig } from '@/mock/appconfigs'
import { merchants, type Merchant } from '@/mock/merchants'

const router = useRouter()
const route = useRoute()

const isCreate = computed(() => route.params.id === 'create')
const qrFormRef = ref()
const saving = ref(false)

// 表单数据
const qrForm = reactive({
  qrName: '',
  qrCode: '',
  qrStatus: 1,
  merchantId: '',
  merchantName: '',
  boundAppId: '',
  validPeriod: '永久有效',
  qrUrl: '',
  qrContent: '',
  generateTime: '',
  bindTime: '',
  createdBy: 'admin',
  createdTime: '',
  updatedTime: ''
})

// 表单验证规则
const qrRules = {
  qrName: [
    { required: true, message: '请输入聚合码牌名称', trigger: 'blur' }
  ],
  qrCode: [
    { required: true, message: '请输入聚合码牌代码', trigger: 'blur' },
    { pattern: /^QR\d{8}\d{3}$/, message: '格式：QR+日期8位+序号3位', trigger: 'blur' }
  ],
  merchantId: [
    { required: true, message: '请选择所属商户', trigger: 'change' }
  ]
}

// 可用商户列表
const availableMerchants = ref<Merchant[]>([])

// 可用APP列表
const availableApps = computed(() => {
  return appConfigs.filter(app => {
    // 如果选择了商户，只显示该商户的APP
    if (qrForm.merchantId) {
      return app.merchantId === qrForm.merchantId && app.status === 1
    }
    return app.status === 1
  })
})

// 选中的商户
const selectedMerchant = computed(() => {
  return availableMerchants.value.find(m => m.merchantId === qrForm.merchantId)
})

// 选中的APP
const selectedApp = computed(() => {
  return availableApps.value.find(app => app.appId === qrForm.boundAppId)
})

// 加载聚合码牌详情（编辑模式）
const loadQrDetail = () => {
  const qrId = route.params.id as string
  const qr = qrCodes.find(q => q.qrId === qrId)
  if (qr) {
    Object.assign(qrForm, qr)
  } else {
    message.error('聚合码牌不存在')
    goBack()
  }
}

// 加载商户列表
const loadMerchants = () => {
  availableMerchants.value = merchants.filter(m => m.status === 1)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 商户选择变化
const handleMerchantChange = (merchantId: string) => {
  if (merchantId) {
    const merchant = merchants.find(m => m.merchantId === merchantId)
    qrForm.merchantName = merchant ? merchant.merchantName : ''

    // 如果当前绑定的APP不属于新选择的商户，则清空绑定
    if (qrForm.boundAppId) {
      const currentApp = appConfigs.find(app => app.appId === qrForm.boundAppId)
      if (!currentApp || currentApp.merchantId !== merchantId) {
        qrForm.boundAppId = ''
        qrForm.bindTime = ''
      }
    }
  }
}

// APP选择变化
const handleAppChange = (appId: string) => {
  if (appId) {
    const app = availableApps.value.find(a => a.appId === appId)
    if (app) {
      qrForm.bindTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    }
  } else {
    qrForm.bindTime = ''
  }
}

// 筛选商户选项
const filterMerchantOption = (input: string, option: any) => {
  const merchant = availableMerchants.value.find(m => m.merchantId === option.value)
  if (!merchant) return false
  return merchant.merchantName.toLowerCase().includes(input.toLowerCase()) ||
         merchant.merchantId.toLowerCase().includes(input.toLowerCase())
}

// 筛选APP选项
const filterAppOption = (input: string, option: any) => {
  const app = availableApps.value.find(a => a.appId === option.value)
  if (!app) return false
  return app.appName.toLowerCase().includes(input.toLowerCase()) ||
         app.merchantName.toLowerCase().includes(input.toLowerCase())
}

// 生成聚合码牌代码
const generateQrCode = () => {
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, '')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  qrForm.qrCode = `QR${date}${random}`
  message.success('聚合码牌代码已生成')
}

// 预览生成效果
const previewGenerated = () => {
  if (!qrForm.qrCode || !qrForm.merchantId) {
    message.warning('请先填写聚合码牌代码和选择商户')
    return
  }

  qrForm.qrUrl = generateQrUrl(qrForm.qrCode)
  qrForm.qrContent = generateQrContent(qrForm.qrCode, qrForm.merchantId)
  message.success('预览已更新')
}

// 测试APP连接
const testConnection = () => {
  if (!qrForm.boundAppId) {
    message.warning('请先绑定APP')
    return
  }
  message.loading('测试连接中...', 1)
  setTimeout(() => {
    message.success('连接测试成功')
  }, 1000)
}

// 保存聚合码牌
const handleSave = async () => {
  try {
    await qrFormRef.value.validate()
    saving.value = true

    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isCreate.value) {
      // 生成必要的字段
      qrForm.qrId = 'QR' + Date.now().toString().slice(-6)
      qrForm.qrUrl = generateQrUrl(qrForm.qrCode)
      qrForm.qrContent = generateQrContent(qrForm.qrCode, qrForm.merchantId)
      qrForm.generateTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
      qrForm.createdTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
      qrForm.updatedTime = qrForm.createdTime

      message.success('新增聚合码牌成功')
    } else {
      qrForm.updatedTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
      message.success('更新聚合码牌成功')
    }

    // 返回列表页
    setTimeout(() => {
      router.push('/development-test/qrcode-management')
    }, 1000)

  } catch (error) {
    message.error('保存失败，请检查表单')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadMerchants()
  if (!isCreate.value) {
    loadQrDetail()
  }
})
</script>

<style scoped>
.qrcode-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.edit-header {
  background: #fff;
  padding: 20px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  padding: 4px 8px;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}

.back-btn:hover {
  color: #1890ff;
  background: #f0f8ff;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.edit-icon {
  font-size: 48px;
  color: #1890ff;
  background: #f0f8ff;
  padding: 16px;
  border-radius: 12px;
}

.edit-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.edit-subtitle {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.edit-content {
  padding: 24px;
}

.form-card,
.preview-card,
.tips-card,
.actions-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
}

.form-section {
  margin-bottom: 32px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.merchant-option,
.app-option {
  padding: 4px 0;
}

.merchant-name,
.app-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.merchant-id {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.app-info {
  font-size: 12px;
  color: #666;
}

.status-option {
  display: flex;
  align-items: center;
}

.qr-preview {
  text-align: center;
}

.qr-visual {
  position: relative;
  padding: 40px 20px;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f4ff 100%);
  border: 2px dashed #1890ff;
  border-radius: 12px;
  margin-bottom: 20px;
  overflow: hidden;
}

.qr-large-icon {
  font-size: 80px;
  color: #1890ff;
  opacity: 0.8;
}

.qr-info-overlay {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 8px;
  border-radius: 6px;
  backdrop-filter: blur(4px);
}

.qr-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.qr-code-text {
  font-family: monospace;
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
}

.qr-details {
  text-align: left;
  background: #f9f9f9;
  padding: 12px;
  border-radius: 6px;
}

.tips-content {
  line-height: 1.6;
}

.ant-alert {
  border-radius: 6px;
}

.ant-form-item {
  margin-bottom: 20px;
}

.ant-input,
.ant-select {
  border-radius: 6px;
}

.ant-card-head-title {
  font-weight: 600;
  color: #333;
}

.ant-descriptions-item-label {
  font-weight: 500;
  color: #666;
}

.ant-descriptions-item-content {
  color: #333;
}

@media (max-width: 768px) {
  .edit-header {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .edit-info {
    gap: 12px;
  }

  .edit-icon {
    font-size: 36px;
    padding: 12px;
  }

  .edit-title {
    font-size: 20px;
  }

  .edit-content {
    padding: 16px;
  }

  .ant-col {
    margin-bottom: 16px;
  }

  .form-section {
    padding: 16px;
    margin-bottom: 20px;
  }
}
</style>